﻿using Diebold.Common.Log;
using TrialManagmentTool.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Configuration;

namespace TrialManagmentTool.Helper
{
    public class WeChatHelper
    {
        string corpid = ConfigurationManager.AppSettings["CorpID"].ToString();
        string corpsecret = ConfigurationManager.AppSettings["Secret"].ToString();

        private static string access_token = "";
        private static DateTime last_token_time;
        private string logsource = "WeChatHelper";
        public string GetToken()
        {
            if (!String.IsNullOrEmpty(access_token) && DateTime.Now <= last_token_time.AddMinutes(29))
            {
                LogManager.Debug(logsource, "last_token:" + access_token + "--last time:" + last_token_time.ToString());
                return access_token;
            }
            else
            {
                #region refer http://www.cnblogs.com/HappyAnt/p/5207739.html;
                string url = String.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", corpid, corpsecret);
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                req.Method = "GET";
                using (WebResponse wr = req.GetResponse())
                {
                    //HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();  
                    StreamReader reader = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
                    string content = reader.ReadToEnd();
                    reader.Close();
                    reader.Dispose();

                    //在这里对Access_token 赋值  
                    AccessToken token = new AccessToken();
                    token = JsonHelper.ParseFromJson<AccessToken>(content);
                    last_token_time = DateTime.Now;
                    access_token = token.access_token;
                }
                return access_token;
                #endregion
            }
        }

        public string ProcessMessage(string sendmessage, string url)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(sendmessage);

            //声明一个HttpWebRequest请求    
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "json";
            Stream reqstream = request.GetRequestStream();
            reqstream.Write(bytes, 0, bytes.Length);
            request.Timeout = 90000;
            request.Headers.Set("Pragma", "no-cache");

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamReceive = response.GetResponseStream();
            Encoding encoding = Encoding.UTF8;

            StreamReader streamReader = new StreamReader(streamReceive, encoding);
            string strResult = streamReader.ReadToEnd();
            streamReceive.Dispose();
            streamReader.Dispose();
            LogManager.Debug("ProcessMessage", strResult);
            return strResult;
        }

        public void SendTextMessage(Wxmessage msg)
        {
            string responsemsg = "{\"agentid\":\"" + msg.AgentID + "\", \"text\":{\"content\":\"" + "收到信息" + msg.Content + "\"},\"msgtype\":\"text\",\"safe\":\"0\",\"touser\":\"" + msg.FromUserName + "\"}";
            ProcessMessage(responsemsg, "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + GetToken());
        }

        public void SendNotifactionMessage(Wxmessage msg,Article article)
        {
            //Article article = new Article() { title = "bt", description = "ms", url = "www.baidu.com", picurl = "http://qydev.weixin.qq.com/wiki/skins/common/images/weixin/weixin_wiki_logo.png" };
            List<Article> listtemp = new List<Article>();
            listtemp.Add(article);
            NewsSendTemp news = new NewsSendTemp() { touser = msg.FromUserName, msgtype = "news", agentid = msg.AgentID, news = new ListArticle { articles = listtemp } };
            string newsresponsemsg = JsonHelper.GetJson<NewsSendTemp>(news);
            ProcessMessage(newsresponsemsg, "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + GetToken());

        }
    }
}